'use strict';

const path = require('path')
const Package = require('@hjy-cli/package')
const log = require('@hjy-cli/log')
const { exec: spawn } = require('@hjy-cli/utils')

// 配置表
const SETTINGS = {
    // init: '@hjy-cli/init'
    init: '@imooc-cli/init'
}

const CACHE_DIR = 'dependencies'

// hjy-cli init --targetPath D:\software\java\workspace\hjy-cli --debug test-project --force
// hjy-cli init test-project --force --debug
async function exec() {
    // 执行：hjy-cli init --targetPath D:/software/java/workspace/test-cli/hjy-cli/commands/init --debug
    // process.env.CLI_TARGET_PATH = D:/software/java/workspace/test-cli/hjy-cli/commands/init
    let targetPath = process.env.CLI_TARGET_PATH
    // process.env.CLI_HOME_PATH = C:\Users\hjy\.hjy-cli
    const homePath = process.env.CLI_HOME_PATH
    let storeDir = ''
    let pkg
    log.verbose('targetPath', targetPath)
    log.verbose('homePath', homePath)

    const cmdObj = arguments[arguments.length - 1]
    // console.log(cmdObj.force) 如果命令有--force，输出true
    const cmdName = cmdObj.name()   // cmdObj.name() = init
    const packageName = SETTINGS[cmdName]   //  @hjy-cli/init
    const packageVersion = 'latest'
    // const packageVersion = '1.1.0'

    if (!targetPath) {
        // 生成缓存路径
        targetPath = path.resolve(homePath, CACHE_DIR)
        storeDir = path.resolve(targetPath, 'node_modules')
        log.verbose('targetPath = ', targetPath);
        log.verbose('storeDir = ', storeDir);

        pkg = new Package({
            targetPath,
            storeDir,
            packageName,
            packageVersion
        })
        console.log('pkg.exists()=', await pkg.exists())
        if (await pkg.exists()) {   // 更新package
            console.log('更新package')
            await pkg.update()
        } else {                    // 安装package
            console.log('安装package')
            await pkg.install()
        }
    } else {
        pkg = new Package({
            targetPath,
            packageName,
            packageVersion
        })
    }
    const rootFile = pkg.getRootFilePath()
    // hjy-cli init test-project --force --debug
    // rootFile = D:/software/java/workspace/test-cli/hjy-cli/commands/init/lib/index.js
    if (rootFile) {
        try {
            // 在当前进程中调用
            // require(rootFile).call(null, Array.from(arguments))

            // 在node子进程中调用
            // 执行代码
            const args = Array.from(arguments)
            const cmd = args[args.length - 1]
            const o = Object.create(null)
            Object.keys(cmd).forEach(key => {
                if (cmd.hasOwnProperty(key) && !key.startsWith('_') && key !== 'parent') {
                    o[key] = cmd[key]
                }
            })
            args[args.length - 1] = o
            const code = `require('${rootFile}').call(null, ${JSON.stringify(args)})`
            // /c静默执行
            // cp.spawn('cmd', ['/c', 'node', '-e', code])
            // -e执行代码
            const child = spawn('node', ['-e', code], {
                cwd: process.cwd(),  // 执行路径
                stdio: 'inherit'    // 展示执行过程中的动态信息
            })
            child.on('error', e => {
                log.error(e.message)
                process.exit(1)
            })
            child.on('exit', e => {
                log.verbose('命令执行成功:' + e)
                process.exit(e)
            })
        } catch (e) {
            log.error(e.message)
        }
    }
}



module.exports = exec;













